package com.hi.hiparty.util;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

import com.hi.hiparty.ui.session.UserSession;
import com.hi.hiparty.ui.session.UserSessionManager;
import com.upyun.api.Uploader;
import com.upyun.api.utils.UpYunException;
import com.upyun.api.utils.UpYunUtils;

public class UpLoaderPicUtil {
	
	public static void uploadUserAvatar(final String fileUrl,final Activity context){
		final UserSession session = UserSessionManager.getUserSession(context);
		if (null == session)
			return;
		String userId = session.getUserid();
		String upUrl = FileUtils.getUserAvatar(userId);
		 
		new UpLoaderPicUtil.UploadTask().execute(
				context,upUrl,fileUrl,new Callback(){
					@Override
					public void execute() {
						// 上传图片成功，更新用户userinfo avatar_url,更新用户session
						UserSessionManager.updataUserAvatar(context, fileUrl);
						Map<String, String> para = new HashMap<String, String>();
						para.put("userid", session.getUserid());
						String avatarUrl = FileUtils.getUserAvatar(session
								.getUserid());
						para.put("avatar", avatarUrl);
						String resultString = HttpUtil.POST(
								ApiHelper.API_USER_AVATAR_UPLOAD, para);
						JSONObject json;
						try {
							json = new JSONObject(resultString);
							if (json.getInt("success") == 1) {
								Log.v("updatePicSuccess", "图片更改完成");
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}	
		});
	}
	
	/**
	 * 成功上传后的处理
	 *
	 */
	public interface Callback{
		public void execute();
	} 
	
	public static class UploadTask extends AsyncTask<Object, Void, Boolean> {
		private String errorMessage ="";
		private String fileUrl;
		private String upUrl;
		private Callback callback=null;
		@SuppressWarnings("unused")
		private Activity activity;
		protected void onPostExecute(final Boolean success) {
			if(errorMessage.isEmpty()){
				//上传图片成功，更新用户userinfo avatar_url,更新用户session
				//UserSessionManager.updataUserAvatar(context, avatarUrl);
				if(null!=callback){
					callback.execute();
				}
			}
		}
		
		@SuppressWarnings("unchecked")
		@Override
		protected Boolean doInBackground(Object... params) {
			activity = (Activity)params[0];
			upUrl = (String)params[1];
			fileUrl = (String)params[2];
			callback = (Callback)params[3];
			Map<String, String> para = new HashMap<String, String>();
			String policy = "";
			try {
				long EXPIRATION = System.currentTimeMillis()/1000 + 1000 * 5 * 10; // 该次请求的授权时间（必须大于当前时间）
				policy = UpYunUtils.makePolicy(upUrl, EXPIRATION, Constants.BUCKET);
			} catch (UpYunException e) {
				errorMessage="签名失败";
				e.printStackTrace();
			}
			para.put("policy", policy);
			//此处是否要再服务端作前面验证?或者用来记录日志
			//para.put("userid", userid);
			//para.put("upUrl", upUrl);
			String signature = "";
			try {
				String resultString = HttpUtil.POST(ApiHelper.API_SIGNATRUE, para);
				JSONObject json = new JSONObject(resultString);
				if (json.getInt("success") == 1 && policy.equals(json.getString("policy"))) {
					signature = json.getString("signature");
				} 
			} catch (Exception e) {
				errorMessage="签名失败";
				return false;
			}
			
			try {
				String res = Uploader
				.upload(policy, signature , Constants.BUCKET, fileUrl);
				if(res.equals(upUrl)) return true;
				Log.v("up2upyun","policy:"+policy+".signature:"+signature+".BUCKET:"+Constants.BUCKET+".fileUrl:"+fileUrl);
				Log.v("up2upyun", res);
			} catch (UpYunException e) {
				//错误码，需参考http://wiki.upyun.com/index.php?title=表单API错误代码表
				errorMessage="图片上传失败.up2upyunerror"+"code:"+e.code+".message:"+ e.message;
				return false;
			}
			return true;
		}
	}
}
